package com.zc.im.connector.handler;

import com.zc.im.common.msg.Msg;
import com.zc.im.connector.listener.ChannelContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Project：im
 * Date：2022/4/22
 * Time：11:23
 * Description：抽象基类
 *
 * @author Challen.Zhang
 * @version 1.0
 */
public abstract class AbstractChannelInboundHandler<T extends Msg> extends SimpleChannelInboundHandler<T> {

    @Autowired
    private ChannelContext channelContext;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, T msg) throws Exception {
        // 存储channel
        channelContext.register(msg.getBaseUserInfo(), ctx.channel());
        channelReadHandle(ctx, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 移除channel缓存
        channelContext.remove(ctx.channel().id());
        super.channelInactive(ctx);
    }

    /**
     * 真正处理逻辑
     *
     * @param ctx ChannelHandlerContext
     * @param msg msg
     */
    protected abstract void channelReadHandle(ChannelHandlerContext ctx, T msg);


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 移除channel缓存
        channelContext.remove(ctx.channel().id());
        super.exceptionCaught(ctx, cause);
    }
}
